package com.gitee.genshin.analyse.data;

import cn.hutool.http.HttpRequest;
import cn.hutool.log.Log;
import com.alibaba.fastjson.JSON;
import com.gitee.genshin.analyse.Main;
import com.gitee.genshin.analyse.data.vo.GenshinData;
import com.gitee.genshin.analyse.data.vo.GenshinDataPage;
import com.gitee.genshin.analyse.data.vo.GenshinDataResponse;

import java.util.List;
import java.util.Optional;

/**
 * @author hongda.li.dlmu@qq.com 2022/7/12 16:25
 */
public class GenshinDataRequester {
    /**
     * 基础请求链接
     */
    private static final String BASE_URL = "https://hk4e-api.mihoyo.com/event/gacha_info/api/getGachaLog";
    /**
     * 祈愿页面复制的URL
     */
    private static final String DATA_API = Main.CONFIG.getStr("data.api");

    private GenshinDataRequester() {
    }

    /**
     * 通过祈愿接口获取祈愿数据
     *
     * @param api 祈愿接口
     * @return 祈愿数据
     */
    public static List<GenshinData> getData(String api) {
        String content = HttpRequest.get(api).execute().body();
        List<GenshinData> genshinDataList = Optional.ofNullable(JSON.parseObject(content, GenshinDataResponse.class))
                .map(GenshinDataResponse::getData)
                .map(GenshinDataPage::getList)
                .orElse(null);
        if (genshinDataList == null){
            Log.get().error("当前API链接为无效链接[{}]", content);
            System.exit(-1);
        }
        return genshinDataList;
    }

    /**
     * 获取祈愿的Api接口
     *
     * @param endId End数据ID
     * @param type  祈愿类型
     * @return Api接口
     */
    public static String getApi(long endId, GenshinDataType type) {
        return BASE_URL
                + DATA_API.substring(DATA_API.indexOf("?"))
                + "&gacha_type=" + type.getCode()
                + "&page=1&size=20&end_id="
                + endId;
    }
}
